<?php
namespace Admin\Controller;
use Think\Controller;
class TypeController extends CommonController {
	public function _initialize(){
		
		parent::check();
	}
	
	//添加页面
	public function add(){
		$this->display();
	}
	
	//添加功能
    public function insert(){
		$name		= I('post.name');
		$typenum	= I('post.typenum');
		
		$rules = array(
		 array('name','require','商品名称必须填写！'), // 商品名称必须填写！
		 array('name','','商品名称已经存在！',1,'unique',1), // 验证用户名是否已经存在
		 array('typenum','require','序号必须填写！'), // 序号必须填写！
		 array('typenum','','序号已经存在！',1,'unique',1), // 验证序号已经存在！
		 
		);

		$Type = M("Type"); // 实例化Type对象
		$res = $Type->validate($rules)->create();
		
		if( $res == false){
			$this->error($Type->getError());
		}
		else{
			$data = array(
				'name'		=> $name,
				'typenum'	=> $typenum
			);
			$res = $Type->add($data);
			if( $res == false){
				$this->error('添加失败');
			}
			$this->success('添加成功');
		}
		
    }
    
    //分类管理页面
    public function tlist(){
		$id		= I('get.id');
		$act	= I('get.act');
		
		$Type = M('Type');
		
		if( $act == 't_del'){
			$ret = $Type->where("id={$id}")->delete();
			
			if( $ret == false){
				$this->error('删除失败');
			}
			$this->success('删除成功');
		}
		
		$list = $Type->order('typenum asc')->select();//查询
		
		if( $list == false){
			$this->error($Type->getError());
		}
		
		$this->assign('list',$list);
		
		
		$this->display();
	}
	
	//子分类管理页面
	public function subtype(){
		$id 	= I('get.id');
		$act	= I('get.act');
		$sub_id = I('get.sub_id');
		
		$Subtype = M('Subtype');
		$Type = M('Type');
		
		if( $act == 't_del'){
			$ret = $Subtype->where("id={$sub_id}")->delete();
			
			if( $ret == false){
				$this->error('删除失败');
			}
			$this->success('删除成功');
		}
		
		$ret = $Type->where("id={$id}")->find();
		$typenum = $ret['typenum'];
		$list = $Subtype->where("typenum={$typenum}")->select();//查询
		
		/*if( $list == false){
			$this->error($Subtype->getError());
		}*/
		
		$this->assign('list',$list);
		$this->assign('id',$id);
		$this->display();
	}
	
	//子分类添加页面
	public function subadd(){
		$id = I('get.id');
		
		$this->assign('id',$id);
		$this->display();
	}
	
	//子分类添加功能
	public function subinsert(){
		$typeid		= I('post.typenum');
		$name		= I('post.name');
		$subnum		= I('post.subnum');

		$Subtype = M("Subtype"); // 实例化Type对象
		$Type = M('Type');
		
		$ret = $Type->where("id={$typeid}")->find();
		$res = $Subtype->create();
		
		if( $res == false){
			$this->error($Subtype->getError());
		}
		else{
			$data = array(
				'typenum'		=> $ret['typenum'],
				'subname'		=> $name,
				'subnum'		=> $subnum
			);
			$res = $Subtype->add($data);
			if( $res == false){
				$this->error('添加失败');
			}
			$this->success('添加成功');
		}
		
    }
}
